package com.wzt.gift.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.wzt.gift.asserts.Assert;
import com.wzt.gift.client.SmsVerifyCodeSendClient;
import com.wzt.gift.domain.User;
import com.wzt.gift.enums.ResponseEnum;
import com.wzt.gift.mapper.UserMapper;
import com.wzt.gift.service.ISmsValidateService;
import com.wzt.gift.util.AjaxResult;
import com.wzt.gift.util.VerificationCodeUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * @Author Zenith
 * @Date 2022/10/12 18:53
 * @Version 1.0
 */
@Service
public class SmsValidateServiceImpl implements ISmsValidateService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SmsVerifyCodeSendClient smsVerifyCodeSendClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public AjaxResult registerSmsValidate(String phone) {
        // 1.手机号是否合法交给JSR303进行校验
        // 2.校验手机号是否已经被注册
        EntityWrapper<User> wrapper = new EntityWrapper<>();
        // 封装查询条件
        wrapper.eq("phone", phone);
        List<User> users = userMapper.selectList(wrapper);
        // 断言手机号没有被注册
        Assert.listIsEmpty(users, ResponseEnum.CODE_PHONE_REGISTERED);

        // 判断是否发送过短信验证码以及是否过了重发时间
        String key = "register_sms_code_" + phone;

        String smsCodeOfRedis = (String) redisTemplate.opsForValue().get(key);
        String code = "";
        if (StringUtils.isEmpty(smsCodeOfRedis)) {
            //2.1 如果不存在就发送新的验证码并记录验证码到Redis中
            String verifyCode = smsVerifyCodeSendClient.sendVerifyCode(phone);
            redisTemplate.opsForValue().set(key, verifyCode + ":" + System.currentTimeMillis(), 5, TimeUnit.MINUTES);
            return AjaxResult.me().setSuccess(true).setMessage("您的验证码为：" + verifyCode);
        } else {
            //2.2 如果存在，判断是否已过重发时间，如果没有，用原来的验证码
            code = smsCodeOfRedis.split(":")[0];
            String time = smsCodeOfRedis.split(":")[1];
            if (System.currentTimeMillis() - new Date(Long.valueOf(time)).getTime() <= 60 * 1000 * 5) {
                return AjaxResult.me().setSuccess(false).setMessage("未过重发时间！");
            }
        }
        return null;
    }
}
